package cn.edu.zime.tjh.iotapp;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.google.zxing.ResultPoint;
import com.journeyapps.barcodescanner.BarcodeCallback;
import com.journeyapps.barcodescanner.BarcodeResult;
import com.journeyapps.barcodescanner.DecoratedBarcodeView;

import java.util.List;

public class ScanActivity extends AppCompatActivity {

    private DecoratedBarcodeView barcodeView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scan);

        barcodeView = findViewById(R.id.barcode_scanner);
        
        // 设置扫码回调
        barcodeView.decodeSingle(new BarcodeCallback() {
            @Override
            public void barcodeResult(BarcodeResult result) {
                if (result.getText() != null) {
                    // 获取扫描到的内容
                    String scanContent = result.getText();
                    
                    // 返回扫描结果
                    Intent resultIntent = new Intent();
                    resultIntent.putExtra("SCAN_RESULT", scanContent);
                    setResult(RESULT_OK, resultIntent);
                    
                    // 提示扫描成功
                    Toast.makeText(ScanActivity.this, "扫描成功", Toast.LENGTH_SHORT).show();
                    
                    // 处理扫描内容
                    processScanResult(scanContent);
                }
            }

            @Override
            public void possibleResultPoints(List<ResultPoint> resultPoints) {
                // 不需要实现
            }
        });
    }
    
    /**
     * 处理扫描结果
     * @param content 扫描到的内容
     */
    private void processScanResult(String content) {
        if (content.startsWith("http://") || content.startsWith("https://") || content.startsWith("www.")) {
            // 如果是网址，直接用浏览器打开
            try {
                Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(content));
                startActivity(browserIntent);
                finish(); // 关闭扫码界面
            } catch (Exception e) {
                // 打开浏览器失败，显示内容弹窗
                showContentDialog("扫描结果（网址）", content);
            }
        } else if (content.startsWith("ws://")) {
//            跳过
            finish();
        } else {
            // 如果不是网址，显示弹窗
            showContentDialog("扫描结果", content);
        }
    }
    
    /**
     * 显示扫描内容的弹窗
     */
    private void showContentDialog(String title, String content) {
        new AlertDialog.Builder(this)
            .setTitle(title)
            .setMessage(content)
            .setPositiveButton("复制", (dialog, which) -> {
                // 复制到剪贴板
                android.content.ClipboardManager clipboard = 
                    (android.content.ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
                android.content.ClipData clip = 
                    android.content.ClipData.newPlainText("扫描结果", content);
                clipboard.setPrimaryClip(clip);
                Toast.makeText(this, "已复制到剪贴板", Toast.LENGTH_SHORT).show();
                finish();
            })
            .setNegativeButton("关闭", (dialog, which) -> finish())
            .setCancelable(false)
            .show();
    }

    @Override
    protected void onResume() {
        super.onResume();
        barcodeView.resume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        barcodeView.pause();
    }
    
    public void back(View v) {
        finish();
    }
}